"use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var app = angular.module("myApp", ['ui.bootstrap']);

var interval_span = 30000;

app.controller("diagnosisController", ['$scope', '$window', '$interval', function ($scope, $window, $interval) {
    $scope.toJSON = function (val) {
        return toJSON(val);
    };

    $scope.showUnknown = false;
    $scope.timerState = 1;
    $scope.faultCheck = {};
    $scope.faultMatched = [];

    $scope.inCheckList = function (signal) {
        return $scope.faultMatched.filter(function (fault) {
            return fault != null && fault.checked;
        }).some(function (fault) {
            return fault.signalPorts.some(function (channel) {
                return channel.id == signal.portId;
            });
        });
    };

    $scope.withUnknown = function (fault) {
        return fault != null && (fault.isMatched || $scope.showUnknown && fault.isUnknown);
    };

    var timestamp = new Date().getTime();
    function fetchKG() {
        if ($scope.timerState == 0) {
            return;
        }
        timestamp += interval_span;
        $.get('http://' + window.location.hostname + ":" + window.basePort + '/rest/work/last/kg/match/' + timestamp, function (data) {
            // data = data.map(f=>{
            //     f.id = f.faultId;
            //     return f;
            // });
            // let gIds = data.map(f=>f.id);
            $scope.matchedResult = data;
            // $scope.faults = FaultNode.faults.filter(f=>gIds.some(id=>id==f.id));
            var lastCheck = {};
            $scope.faultMatched.forEach(function (f) {
                lastCheck[f.id] = f.checked;
            });
            $scope.faultMatched = data.map(function (f) {
                f.checked = lastCheck[f.id] || false;
                return f;
            });
            $scope.$apply();
        });
    }

    function fetchSignal() {
        if ($scope.timerState == 0) {
            return;
        }
        $.get('http://' + window.location.hostname + ":" + window.basePort + '/rest/work/last/signal/' + timestamp, function (data) {
            $scope.signals = data;
            // $scope.signals2 = _.flatMap($scope.signals,obj=>{
            //     let val = obj;
            //     if(obj.value && obj.value instanceof Array){
            //         return obj.value.map((vl,id)=>{
            //             return {
            //                 componentName:val.component.name+(id+1),
            //                 featureType:val.featureType,
            //                 value:vl
            //             }
            //         });
            //     }else {
            //         return [
            //             {
            //                 componentName:val.component.name,
            //                 featureType:val.featureType,
            //                 value:val.value
            //             }
            //         ];
            //     }
            // });
            // console.info($scope.signals2);
            $scope.$apply();
        });
    }

    fetchKG();
    fetchSignal();

    $interval(fetchKG, interval_span);
    $interval(fetchSignal, interval_span);

    function showToReport(faultId, filename, title) {
        var result = $scope.matchedResult.filter(function (res) {
            return res.id == faultId;
        })[0];
        var matchedNodes = void 0,
            unknownNodes = void 0,
            channels = void 0;
        if (result != null) matchedNodes = angular.toJson(result["matched"], false);else matchedNodes = "[]";

        if (result != null) unknownNodes = angular.toJson(result["unknown"], false);else unknownNodes = "[]";

        if (result != null) {
            channels = angular.toJson(result["signalPorts"].map(function (ch) {
                var value = _.find($scope.signals, function (port) {
                    return port.portId == ch.id;
                }).value;
                ch.value = value;
                return ch;
            }), false);
        } else {
            channels = "[]";
        }

        var jumpTo = filename + "?faultId=" + faultId + "&matchedNodes=" + encodeURI(matchedNodes) + "&unknownNodes=" + encodeURI(unknownNodes) + "&timestamp=" + timestamp + "&last_timestamp=" + result.last_timestamp + "&reportId=" + result.reportId + "&channels=" + encodeURI(channels);
        if (isInFrame()) {
            pushUrl("../fault/" + jumpTo, title);
        } else {
            $window.open(jumpTo);
        }
    }

    $scope.showFaultReport = function (faultId) {
        showToReport(faultId, "report.html", "诊断报告");
    };

    $scope.showFaultTree = function (faultId) {
        showToReport(faultId, "FaultExplain.html", "诊断解释");
    };

    $scope.jumpToHuman = function (fid) {
        alert("转到人工！！！");
    };

    $scope.toLatest = function () {
        timestamp = new Date().getTime();
    };
}]);

var toJSON = function toJSON(obj) {
    var cache = [];
    return JSON.stringify(obj, function (key, value) {
        if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // Circular reference found, discard key
                return;
            }
            // Store value in our collection
            cache.push(value);
        }
        return value;
    });
};

var isInFrame = function isInFrame() {
    return localStorage.getItem("useInFrame") == "true";
};

var pushUrl = function pushUrl(url, title) {
    var stackStr = localStorage.getItem("tabStack") || "[]";
    var stack = JSON.parse(stackStr);
    stack.push({
        url: url,
        title: title
    });
    stackStr = JSON.stringify(stack);
    localStorage.setItem("tabStack", stackStr);
};

app.filter('startX', [function () {
    return function (array, size) {
        if (array.length <= size) return array.map(function (x) {
            return x.toFixed(2);
        }).join(",");
        return array.slice(0, 2).map(function (x) {
            return x.toFixed(2);
        }).join(",") + "等" + array.length + "项";
    };
}]);
